function export_bin( samples, classes, directory )
%EXPORT_BIN Exports samples and classes for mRMR turbo in binary format.
%   Exports binary sample matrix and classes matrix to two separate files
%   that can be loaded into optimized mRMR implementation for
%   binary feature problems.
%   If matlabpool is open, it will use all available computing power to
%   compress data (which may take few minutes with very large arrays).

    % plan 
    %disp('Planning...');
    fSamples = [directory '/samples.sc' ];
    fClasses = [directory '/classes.sc' ];
    
    
    % export classes
    disp('   Exporting headers...');
    
    fh = fopen(fClasses, 'w');
    headline = [ int2str(size(samples, 1)), ' ', int2str(size(samples, 2)), '\n'  ];
    fprintf(fh, headline);
    fprintf(fh, [sprintf('%.0f ', classes'), '\n'] );
    fclose(fh);
    
    % export samples
    disp('   Exporting samples...');
    saveBin(fSamples, samples);
    
end


function saveBin(fileName, arr) 
%EXPORT_BIN Export input data for mRMR turbo in binary format

    arr = arr(:)';
    
    len = size(arr, 2); % vector length;
    chunks = ceil(len / 8);
    toSave = zeros(chunks, 1);
    
    for chunk=0:chunks-1
        from = chunk*8 + 1;
        to = (chunk+1)*8;
        
        if to > len
           % last byte
           to = len; 
           toConv = arr(from:to);
           % pad with zeros
           toConv = [toConv zeros(1, 8 - size(toConv, 2)) ];
        else
           toConv = arr(from:to);
        end
        
       byte = b2d(toConv);
       toSave(chunk + 1) = byte;
       
    end
    
    % write all data from buffer to file
    fid = fopen(fileName,'wb');
    fwrite(fid,toSave);
    fclose(fid);
end

% Convert a binary array to a decimal number
% 
% Similar to bin2dec but works with arrays instead of strings and is found to be 
% rather faster
% From: https://www.mathworks.com/matlabcentral/fileexchange/26447-efficient-convertors-between-binary-and-decimal-numbers
function y = b2d(x)
    z = 2.^(length(x)-1:-1:0);
    y = sum(x.*z);
end
